package com.appspot.smartgan.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.util.Log;

class AsyncConnection extends AsyncTask<String, String, String> {

	@Override
	protected String doInBackground(String... params) {
		try {
			// creating the url
			URL server = new URL(params[0]);
			
			// opening the connection
			URLConnection connection;
			connection = server.openConnection();
			
			// get data about the connection
			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();
			
			// connection was properly established
			if (responseCode == HttpURLConnection.HTTP_OK) {
				BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
				String line;
				String input = "";
				while ((line = in.readLine()) != null) {
					input += line;
					Log.d("RESPONSE", line);
				}
				
				in.close();
				
				return input;
			} else {
				Log.w("SMARTGAN", "Connection to server failed");
				Log.w("SMARTGAN", "" + responseCode);
				return "-1";
			}
		} catch (MalformedURLException e) {
			Log.e("SMARTGAN", "MalformedURLException: " + e.getMessage());
		} catch (IOException e) {
			Log.e("SMARTGAN", "IOException: " + e.getMessage());
		} catch (Exception e) {
			Log.e("SMARTGAN", "Exception: " + e.getMessage());
		} finally { }
		
		return "-1";
	}

}
